package com.zx.common.async.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor;
import java.util.function.Supplier;

/**
 * CompletableFuture异步任务服务类
 * 基于CompletableFuture提供更灵活的异步编程支持
 *
 * @author zhou xun
 * @since 2025-10-15
 */
@Slf4j
@Component
public class CompletableFutureAsyncService {

    /**
     * 使用指定的线程池执行异步任务
     *
     * @param task     任务内容
     * @param executor 线程池
     * @param <T>      返回值类型
     * @return CompletableFuture
     */
    public <T> CompletableFuture<T> executeAsync(Supplier<T> task, Executor executor) {
        return CompletableFuture.supplyAsync(task, executor)
                .exceptionally(throwable -> {
                    log.error("执行异步任务时发生错误", throwable);
                    throw new RuntimeException(throwable);
                });
    }

    /**
     * 使用指定的线程池执行无返回值的异步任务
     *
     * @param task     任务内容
     * @param executor 线程池
     * @return CompletableFuture
     */
    public CompletableFuture<Void> executeAsync(Runnable task, Executor executor) {
        return CompletableFuture.runAsync(task, executor)
                .exceptionally(throwable -> {
                    log.error("执行异步任务时发生错误", throwable);
                    throw new RuntimeException(throwable);
                });
    }
}